package com.androway.utils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;

public class FragmentRegister
{
	private class FragmentInfo
	{
		private Constructor<?> constructor;
		private String title;
		private String key;

		public FragmentInfo(Class<?> clazz, String title, String mkey) throws NoSuchMethodException
		{
			this.constructor = (Constructor<?>) clazz.getConstructor();
			this.title = title;
			this.key = mkey;
		}

		public Constructor<?> getConstructor()
		{
			return constructor;
		}

		public String getTitle()
		{
			return title;
		}

		public String getKey()
		{
			return key;
		}
	}

	private List<FragmentInfo> fragmentInfoList = new ArrayList<FragmentInfo>();

	public FragmentRegister()
	{

	}

	public String getFragmentTitle(int position)
	{
		if (position > fragmentInfoList.size() || position < 0)
			return null;
		return fragmentInfoList.get(position).getTitle();
	}

	public Fragment getFragment(int position)
	{
		System.out.println(position);
		if (position > fragmentInfoList.size() || position < 0)
			return null;
		try
		{
			return (Fragment) fragmentInfoList.get(position).getConstructor().newInstance();
		}
		catch (IllegalArgumentException e)
		{
			return null;
		}
		catch (InstantiationException e)
		{
			return null;
		}
		catch (IllegalAccessException e)
		{
			return null;
		}
		catch (InvocationTargetException e)
		{
			return null;
		}
	}

	public String getKey(int position)
	{
		if (position > fragmentInfoList.size() || position < 0)
			return null;
		return fragmentInfoList.get(position).getKey();
	}

	public void register(Class<?> clazz, String title, String key)
	{
		try
		{
			fragmentInfoList.add(new FragmentInfo(clazz, title, key));
		}
		catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		}
	}

	public int getSize()
	{
		return (fragmentInfoList.size());
	}
}
